import glob
import uuid
import logging
import paho.mqtt.client as mqtt
import json
import netifaces

from setting import *

LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
logger = logging.getLogger(__name__)


def get_mac_address():
    """获取系统的MacAddress"""

    if glob.glob("/root/.mac"):
        
        with open('/root/.mac') as f:

            mac = f.read().strip()
    else:    
        node = uuid.getnode()

        mac = uuid.UUID(int=node).hex[-12:]

    return mac


def left_move_bit(move_str: str, move_number: int):
    '''将指定位置的bit值变为0'''
    up_data = int(move_str, 16)

    temp = 0xfffe

    for i in range(move_number):

        temp = temp<<1 | 0x0001

    up_data = up_data&temp

    return up_data


def get_derive_status(Lbyte: bytes, Hbyte: bytes):
    '''获取设备开关状态'''
    up_data = Hbyte << 8 | Lbyte
    sw_status = 0
    for i in range(5):
        if (up_data & (0x01 << (i * 2))) != 0:
            sw_status = sw_status | 0x01 << i
            print(i)
    # print(hex(sw_status))
    return sw_status


def ctrl_derive_sw(switch_number: int, sw_status: int, OpenorClose: int):
    if OpenorClose == 1:
        sw_status = sw_status | 0x01 << switch_number
    else:
        temp = 0xfffe
        for i in range(switch_number):

            temp = temp << 1 | 0x0001
        sw_status = sw_status & temp
    return sw_status


def hex_to_bin(hex_num): 
    '''输入16进制反回二进制类型的字符串

    >>> hex_to_bin(int('8', 16))
    >>> '00001000'
    
    '''
    bin_str = bin(hex_num)[2:] # 去除前"0b"

    pre = ''
    for i in range(8 - len(bin_str)):

        pre+='0'

    return pre + bin_str

def binary_to_hex(binary_string):
    '''输入二进制的字符串返回16进制的字符串

    >>> binary_to_hex("00000101")
    >>> 5
    
    '''
    integer = int(binary_string, 2)
    hex_string = hex(integer)
    return hex_string[2:]  # 去除前缀 "0x"


def binary_site_change(binary_string, index: int, change_value):
    '''
    >>> binary_site_change('00000101', 0, 7)
    >>> '10000101'
    >>> binary_site_change('10000101', 5, 1)
    >>> '10100001'
    '''

    binary_list = list(binary_string)

    binary_list.reverse()

    binary_list[index] = str(change_value)

    binary_list.reverse()

    return ''.join(binary_list)

def parse_command_to_ascII(command: bytearray) -> str: # 命令解释成ascII命令格式
    '''
    >>> parse_command_to_ascII(bytearray([0x16, 0x01, 0x00, 0x00, 0x00, 0x01]))
    >>> 313630313030303030303031
    '''

    res = ""

    for i in command:

        v = hex(i).replace("0x", "").upper()

        val = v if len(v) == 2 else "0"+ v

        for ii in val:

            res += str(hex(ord(ii))).replace("0x", '')

    return res

def parse_hex_str_to_bytearray(hex_str: str) -> bytearray: # 将16进制的字符串变成二进制
    '''
    >>> parse_hex_str_to_bytearray("0301070610FFFF")
    bytearray(b'\x03\x01\x07\x06\x10\xff\xff')
    '''

    bytearray_data = bytearray.fromhex(hex_str)

    return bytearray_data

def dict_factory(cursor, row): # sqlite3 工厂函数
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d  


def parse_ascII_to_command(ascII_str: str) -> bytearray:

    '''ascII字符串转成命令
    >>> parse_ascII_to_command("313630313030303030303031")
    >>> bytearray(b'160100000001')
    '''
    command = bytearray()

    for i in range(0, len(ascII_str), 2):
        hex_val = chr(int(ascII_str[i:i+2], 16))
        command.append(ord(hex_val))

    return command

def send_data_to_mqtt(data, topic):

        '''发送数据到mqtt
        data :{
                    "data": command,
                    "devaddr": devaddr,
                    "port": 12
                }
        '''
        # 连接 MQTT 代理
        client = mqtt.Client()
        # client.connect("mqtt_broker_address", 1883)  # 替换为您的 MQTT 代理地址和端口

        # 建立连接
        client.connect(MQTT_LOCAL_HOST, MQTT_LOCAL_PORT, 60)


        payload = json.dumps(data)

        # 发布数据到指定主题
        client.publish(topic, payload)

        # 断开 MQTT 连接
        client.disconnect()

def get_network_info(interface="eth0"):
    """
    >>> get_network_info("eth0")
    >>> {'ip_address': '192.168.88.200', 'netmask': '255.255.255.0', 'gateway': '192.168.88.1'}
    """
    info = {}
    addrs = netifaces.ifaddresses(interface)
    
    if netifaces.AF_INET in addrs:
        info['ip_address'] = addrs[netifaces.AF_INET][0]['addr']
        info['netmask'] = addrs[netifaces.AF_INET][0]['netmask']
        info['gateway'] = netifaces.gateways()[netifaces.AF_INET][0][0]
        # info['broadcast'] = addrs[netifaces.AF_INET][0]['broadcast']

        with open("/root/.self_host", "w") as f:

            f.write(info['ip_address'])
    else:
        
        return None
    
    return info

if __name__ == "__main__":

    print(get_mac_address())

    # x = get_derive_status(0x40, 0x01)

    # print(x)

    # print(bin(x))

    # print(hex_to_bin(int('8', 16)))

    # print(binary_to_hex('00001010'))

    # parse_command_to_ascII(bytearray([0x16, 0x01, 0x00, 0x00, 0x00, 0x01]))

    x = parse_ascII_to_command("3036423930373130303337353543")

    print(x)


